package com.itheima.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 定义拦截器
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override//controller之前目标资源方法运行前运行，返回true:放行，放回false，不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        log.info("请求的url：{}",url);
        if(url.contains("login")){

            log.info("登陆操作放行");
            return true;
        }

        String jwt =request.getHeader("token");

        if(!StringUtils.hasLength(jwt)){
            log.info("token为空");
            Result error = Result.error("NOT_LOGIN");
            //要的是json格式数据 之前是在controller层加上RestController就能把Result自动转换成json返回前端 alibaba FastJSON工具包
            String notLogin = JSONObject.toJSONString(error);
            //response响应浏览器
            response.getWriter().write(notLogin);
            return false;
        }

        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {//jwt解析失败
            e.printStackTrace();
            log.info("令牌解析失败,返回未登录的错误信息");
            Result error = Result.error("NOT_LOGIN");
            //要的是json格式数据 之前是在controller层加上RestController就能把Result自动转换成json返回前端 alibaba FastJSON工具包
            String notLogin = JSONObject.toJSONString(error);
            //response响应浏览器
            response.getWriter().write(notLogin);
            return false;
        }

        log.info("放行");
        return  true;
    }

    @Override//controller之后目标资源方法运行后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("post");
    }

    @Override//视图渲染完毕后运行，最后运行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("after");
    }
}
